import axios from 'axios'

const service = axios.create({
    //设置响应时返回数组流
    responseType:'arraybuffer'
});

service.interceptors.request.use(config=>{
    /*登录验证*/
    config.headers['Authorization']=window.sessionStorage.getItem('tokenStr');
    return config;
},error=>{
      console.log(error);
});


service.interceptors.response.use(resp=>{
    const headers=resp.headers;
    /*正则表达式*/
    let reg =RegExp(/application\/json/);
    if (headers['content-type'].match(reg)){
        //普通请求时 arraybuffer 转为json对象
       resp.data=unitToString(resp.data);
    }else {
        //下载文件请求时
        let  fileDownload = require('js-file-download');//插件
        /*content-disposition:attachment;filename=%E5%91%98%E5%B7%A5%E8%A1%A8.xls*/
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1];
        let contentType = headers['content-type'];
        //对计算机可读的编码进行解码为我们可读的编码
        fileName =decodeURIComponent(fileName);
        //使用插件下载
        fileDownload(resp.data,fileName,contentType);
    }
    }, error => {
    console.log(error);
})

function unitToString(unitArray){
    //将流数据8位整数类型转换成流字符串编码
    let encodedString = String.fromCharCode.apply(null,new Uint8Array(unitArray));
    //escape流字符串编码转成计算机可读的字符串编码,decodeURIComponent解码我们可读
    let decodeString = decodeURIComponent(escape(encodedString));
    //将我们可读编码转成json对象 返回
    return JSON.parse(decodeString);
}

let base ='';
export  const downloadRequest=(url,params)=>{
    return service({
       methods:'get',
       url:`${base}${url}`,
       data:params
    });
}

export default service;
